<template>
  <div class="login-wrapper">
    <img src="@/assets/images/login_bg.jpg" class="login-bg" />
    <div class="login-box" v-loading="loading">
      <div class="sys-title">欢迎登录</div>
      <div class="title">车位管理系统</div>
      <div class="content">
        <el-form ref="userFormRef" :rules="rules" :model="userForm" class="user-form">
          <el-form-item prop="username">
            <el-input size="large" v-model.trim="userForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              size="large"
              type="password"
              v-model.trim="userForm.password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input size="large" v-model.trim="userForm.code" placeholder="请输入验证码">
              <template #suffix>
                <img :src="codeImg" class="captcha" @click="getCode" alt="验证码" />
                <!-- <div class="captcha" @click="getCode">{{ cCode }}</div> -->
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-button size="large" class="login-btn" type="primary" @click="handleLogin" round>登录</el-button>
      </div>
      <!-- <div class="foot">智阔科技</div> -->
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import Cookies from 'js-cookie'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const router = useRouter()

// 登录
const loading = ref(false)
const userFormRef = ref()
const userForm = reactive({
  username: '', //账号
  password: '',
  code: '',
  uuid: '', // uuid
})
const checkLoginCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('验证码不能为空'))
  } else if (value.toLowerCase() !== cCode.value.toLowerCase()) {
    callback(new Error('验证码输入错误'))
  } else {
    callback()
  }
}
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  loginPwd: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  code: [{ required: true, validator: checkLoginCode }],
}
const handleLogin = async () => {
  loading.value = true
  try {
    await userFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const params = { ...userForm }
        const loginMsg = await $request.post('/api-parking/login', { params })
        Cookies.set(process.env.envConfig.TOKEN, `Bearer ${loginMsg.token}`)
        await userStore.getUserInfo()
        router.push({ path: '/' })
      } else {
        getCode()
        ElMessage.error({ message: '验证码校验不通过,请重新输入', duration: 1000 })
      }
    })
  } finally {
    loading.value = false
  }
}

// 高度计算
const domHright = ref(258)
const resize = () => {
  nextTick(() => {
    // 获取 class 名为 login-wrapper 的 DOM 元素
    const loginWrapper = document.querySelector('.login-wrapper')
    if (loginWrapper) {
      const height = loginWrapper.clientHeight // 获取元素的高度
      domHright.value = `${height * 0.55}px`
    } else {
      console.log('未找到 class 为 login-wrapper 的元素')
    }
  })
}
const addResizeListener = (fn) => {
  window.onresize = () => {
    fn()
  }
}

const cCode = ref('')
const codeImg = ref('')
async function getCode() {
  // 生成验证码
  const res = await $request.get('/api-parking/captchaImage')

  codeImg.value = 'data:image/jpeg;base64,' + res.img
  cCode.value = res.code
  userForm.uuid = res.uuid
  userForm.code = ''
}
onMounted(() => {
  resize()
  getCode()
  addResizeListener(resize)
})
onBeforeUnmount(() => {
  window.onresize = null
})
</script>

<style lang="scss" scoped>
.login-wrapper {
  width: 100vw;
  height: 100vh;
  min-width: 1280px;
  min-height: 588px;
  overflow: hidden;
  position: relative;
  display: flex;
  .login-bg {
    height: 100%;
    width: auto;
    object-fit: cover;
    flex-shrink: 0;
  }
  .login-box {
    flex: 1;
    height: 100%;
    min-width: 360px;
    background: #fff;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    padding: 200px 130px 20px 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .sys-title {
      font-family:
        PingFang SC,
        PingFang SC;
      font-weight: 600;
      font-size: 24px;
      color: #262729;
      line-height: 36px;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-bottom: 9px;
    }
    .title {
      font-family:
        PingFangSC,
        PingFang SC;
      font-weight: 400;
      font-size: 21px;
      color: #262729;
      margin-bottom: 24px;
    }
    .content {
      flex: 1;
      .el-form-item {
        margin-bottom: 24px;
      }
    }
    .foot {
      text-align: center;
      font-size: 14px;
      font-weight: 400;
      color: #8c8c8c;
    }
    .login-btn {
      width: 100%;
    }
  }
}
.captcha {
  // height: 100%;
  height: 38px;
  width: auto;
  background: #fff;
  color: #3c66f6;
  margin-right: -14px;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  font-size: 18px;
  cursor: pointer;
}
:deep(.el-input__wrapper) {
  background-color: #f5f6f8;
}
</style>
